package com.suse.controller;

import com.suse.dto.EmployeeDto;
import com.suse.pojo.Employee;
import com.suse.service.EmployeeService;
import com.suse.util.ResultVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

@RestController
@RequestMapping("/employee")
public class EmployeeController {

    @Autowired
    EmployeeService service;
    //修改员工信息
    @PostMapping("/update")
    public ResultVo update(@RequestBody Employee u, HttpServletRequest request) {
        return service.update(u,request);
    }
    //删除员工
    @GetMapping("/delete")
    public ResultVo delete(Integer id) {return service.delete(id);}
    //查询员工
    @GetMapping("/search")
    public ResultVo search(EmployeeDto dto) {
        return service.search(dto);
    }
    //新增员工，验证合法性
    @GetMapping("/add")
    public ResultVo add(@Valid Employee u, BindingResult result) {
        //如果字段不合法
        if (result.hasErrors()) {
            for(ObjectError error : result.getAllErrors()) {
                //获取错误信息
                String message = error.getDefaultMessage();
                return ResultVo.error(message);
            }
        }
        //调用EmployeeService接口实现类的add方法
        return service.add(u);
    }
    //登录
    @PostMapping("/login")
    public ResultVo login(@RequestBody Employee u, HttpServletRequest request) {
        return service.login(u, request);
    }
    //发送验证码
    @GetMapping("/sendCode")
    public ResultVo sendCode(String email,HttpServletRequest request) {
        return service.sendCode(email, request);
    }
    //验证码验证
    @GetMapping("/verify")
    public ResultVo verify(String code, HttpServletRequest request) {
        return service.verify(code, request);
    }
    //上传文件
    @PostMapping("/uploadFile")
    public ResultVo uploadFile(@RequestParam("file") MultipartFile file, HttpServletRequest request){
        return service.fileUpload(file, request);
    }
    @GetMapping("/query")
    public ResultVo query(EmployeeDto dto) {
        return service.search(dto);
    }
}
